package com.adb.ww2.fragment;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.app.ListFragment;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;

import com.adb.ww2.Log;
import com.adb.ww2.R;
import com.adb.ww2.ui.DetailsFragmentActivity;

public class ListViewFragment extends ListFragment {
	
	public static String TAG = ListViewFragment.class.getCanonicalName();
	
	boolean mDualPane;
	int mCurCheckPosition = 0;
	 
	/**
	 * mCallback instance of the OnHeadlineSelectedListener interface.
	 */
	OnHeadlineSelectedListener mCallback;
	
	
	/**
	 * User interface has callback that Fragment Activity must implements 
	 * Container Activity must implement this interface
	 */
	public interface OnHeadlineSelectedListener {
        public void onArticleSelected(int position);
    }
	
	
	@Override
	public void onAttach(Activity activity) {
		super.onAttach(activity);
		 // This makes sure that the container activity has implemented
        // the callback interface. If not, it throws an exception
        try {
            mCallback = (OnHeadlineSelectedListener) activity;
        } catch (ClassCastException e) {
            throw new ClassCastException(activity.toString()
                    + " must implement OnHeadlineSelectedListener");
        }
	}
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
	}
	/**
	 * List Fragment it shelf return view so no need to use onCreateView callback of Fragment 
	 * 
	 */
	
	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);
		Activity mActivity = getActivity();
		
		if(mActivity != null){
			
			 // Populate list with our static array of titles.
			 setListAdapter(new ArrayAdapter<String>(mActivity,
	                    android.R.layout.simple_list_item_1, com.adb.ww2.Constant.TITLES));
			 
			 View detailsFrame = getActivity().findViewById(R.id.details);
			 //Return true if in Landscape mode 
			 mDualPane = detailsFrame != null && detailsFrame.getVisibility() == View.VISIBLE;
			 
			 //If saved Instance State is not null means 
		 	if (savedInstanceState != null) {
	            // Restore last state for checked position.
	            mCurCheckPosition = savedInstanceState.getInt("curChoice", 0);
	        }

	        if (mDualPane) {
	            // In dual-pane mode, the list view highlights the selected item.
	            getListView().setChoiceMode(ListView.CHOICE_MODE_SINGLE);
	            // Make sure our UI is in the correct state.
	            showDetails(mCurCheckPosition);
	        }
		}
		
	}
	
	@Override
	public void onDestroy() {
		super.onDestroy();
	}
	@Override
	public void onDestroyView() {
		super.onDestroyView();
	}
	@Override
	public void onDetach() {
		super.onDetach();
	}
	
	/**
	 * This callback is called when List Item is click by user
	 * 
	 */
	
	
	@Override
	public void onListItemClick(ListView l, View v, int position, long id) {
		super.onListItemClick(l, v, position, id);
		
		//TODO fragment uses the callback interface to deliver the event to the parent activity.
		Log.debug(TAG,"[ PASS POSTION]" + position);
		mCallback.onArticleSelected(position);
		
	}
	
	 /**
     * Helper function to show the details of a selected item, either by
     * displaying a fragment in-place in the current UI, or starting a
     * whole new activity in which it is displayed.
     */
	void showDetails(int index) 
	{
        mCurCheckPosition = index;

        if (mDualPane) {
        	
            // We can display everything in-place with fragments, so update
            // the list to highlight the selected item and show the data.
            getListView().setItemChecked(index, true);

            // Check what fragment is currently shown, replace if needed.
            DetailViewFragment details = (DetailViewFragment)
                    getFragmentManager().findFragmentById(R.id.details);
            if (details == null || details.getShowIndex() != index) {
                // Make new fragment to show this selection.
                details = DetailViewFragment.newInstance(index);

                // Execute a transaction, replacing any existing fragment
                // with this one inside the frame.
                FragmentTransaction ft = getFragmentManager().beginTransaction();
                ft.replace(R.id.details, details);
                ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
                ft.commit();
            }

        } else {
            // Otherwise we need to launch a new activity to display
            // the dialog fragment with selected text.
            Intent intent = new Intent();
            intent.setClass(getActivity(), DetailsFragmentActivity.class);
            intent.putExtra("index", index);
            startActivity(intent);
        }
    }
}
